package com.qf.fmall2204.user.controller;

import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.jwt.JWT;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.fmall2204.constants.Constants;
import com.qf.fmall2204.user.entity.User;
import com.qf.fmall2204.user.service.IUserService;
import com.qf.fmall2204.vo.ResultVo;
import com.qf.fmall2204.vo.UserRegistVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.Date;

/**
 * <p>
 * 用户  前端控制器
 * </p>
 *
 * @author dong
 * @since 2023-04-20
 */
@CrossOrigin  // 跨域处理
@RestController
@RequestMapping("/user")
@Slf4j // 打印日志
@Validated
public class UsersController {

    @Autowired
    IUserService userService;

    @GetMapping("/login")
    public ResultVo login(@NotBlank String username,@NotBlank String password) throws Exception {
        log.debug("入参为:username={},password={}",username,password);

        // 1shiro 登录
        // 1.1 获取shiro的核心对象
        Subject subject = SecurityUtils.getSubject();

        // 1.2 shiro登录
        subject.login(new UsernamePasswordToken(username,password));

        // 返回json
        // code, msg, data(userId,username,userImg)
        User user = (User) subject.getPrincipal();

        String userjson = new ObjectMapper().writeValueAsString(user);
//        String md5user = DigestUtil.md5Hex(userjson);
        String token = JWT.create()
                .setKey("qfsyjava2204".getBytes())
                .setSubject(userjson)
                .setPayload("perms","index:get")
                .setExpiresAt(new Date(System.currentTimeMillis() + 1000000))
                .sign();

        return new ResultVo(Constants.SUCCESS_CODE, token, user);
    }


    @PostMapping("/regist")
    public ResultVo regist(@Valid @RequestBody UserRegistVo userRegistVo){

        log.debug("入参为:userRegistVo={}",userRegistVo);
        //1. 校验参数 （两次密码是否一致）
        String password = userRegistVo.getPassword();
        String repassword = userRegistVo.getRepassword();
        if (!password.equals(repassword)){
            throw new RuntimeException("两次密码不一致，注册失败");
        }

        //2. 调用service层方法，完成注册逻辑
        userService.regist(userRegistVo);
        log.debug("注册用户成功");
        //3. 返回前端需要的json
        return new ResultVo(Constants.SUCCESS_CODE);

    }

    @GetMapping("/get/{id}")
    public User getById(@PathVariable("id") Integer id){
        User user = userService.getById(id);
        return user;
    }

}
